<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Property;
use App\Models\PropertyInfo;
use App\Models\Turn;
use App\Library\ETH\EthereumFunction;
use App\Library\BTC\BitcoinFunction;
use App\Library\OBA\ObaFunction;
use Exception;
use DB;
use App\Models\Message;

/**
 * 充币判断是否成功
 */
class RechargeExec extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'recharge:exec';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //查出所有充币记录（type为1 status为1）类型为充币，状态为进行中, 解锁时间已到
        $turns = Turn::where(['type' => 1, 'status' => 1])
            //->where('unlock_time', '<=', time())
            ->get();
        //dump(collect($turns)->count());
        if (collect($turns)->count() > 0) {

            foreach ($turns as $turn) {

                try {
                    if (!in_array($turn->currency->name_en, ['ETH', 'BTC', 'LTC', 'DGC', 'OBA'])) {
                        throw new Exception('不支持该币种');
                    }
                    //以太币
                    if ($turn->currency->name_en == 'ETH') {
                        $currencyHandle = new EthereumFunction();
                        //当前余额
                        $balance = $currencyHandle->getBalanceByAddress($turn->wallet->address);
                    }
                    //比特币，莱特币，狗币
                    if (in_array($turn->currency->name_en, ['BTC', 'LTC', 'DGC'])) {
                        $currencyHandle = new BitcoinFunction($turn->currency->name_en);
                        //当前余额
                        $balance = $currencyHandle->getBalanceByAddress($turn->wallet->address);
                    }
                    if ($turn->currency->name_en == 'OBA') {
                        $currencyHandle = new ObaFunction();
                        //当前余额
                        $balance = $currencyHandle->getBalanceByAddress($turn->wallet->address);
                    }
                    //验证用户钱包地址
                    $check = $currencyHandle->addressValidator($turn->wallet_address);
                    if (!$check) {
                        throw new Exception('地址不合法');
                    }
                    //获取分配钱包时锁定的余额
                    $locked = $turn->wallet->block_balance;

                    //dump($balance, $locked);
                    //当前余额大于锁定余额，代表有充币
                    //开启事务
                    DB::beginTransaction();
                    
                    //如果没到解锁时间
                    if ($turn->unlock_time < time()) {
                        if ($balance > $locked) {
                            //充币金额=当前余额-锁定余额
                            $num = ($balance - $locked);
                            //echo $num;
                            //增加用户对应资产
                            $property = Property::where(['cid' => $turn->cid, 'uid' => $turn->uid])->first();
                            if ($num>=$turn->currency->into_value){//产品需求--小于最小转入值将不打到用户账户中
                                $property->increment('balance', $num); //增加可用资产
                                $property->increment('total', $num); //增加总资产
                            }

                            //Property::where(['cid' => $turn->cid, 'uid' => $turn->uid])->increment('balance', $num);
                            //增加资产详情
                            PropertyInfo::create([
                                'uid' => $turn->uid,
                                'cid' => $turn->cid,
                                'oid' => $turn->id,
                                'num' => $num,
                                'note' => '充币',
                                'price' => 0,
                                'total' => $num,
                                'proc' => 0,
                                'type' => 1,
                                'deal_type' => 1,
                                'status' => 1,
                            ]);
                            //修改转入数量和实际数量
                            $turn->increment('num', $num);
                            $turn->increment('real_num', $num);
                            $turn->update([
                                'status' => 2,
                            ]);
                            //将钱包地址修改为解锁
                            $turn->wallet->update([
                                'status' => 0,
                            ]);
                            //写入消息
                            $msgArr = [
                                'msg_id' => 14,
                                'uid' => $turn->id,
                                'message' => [$turn->currency->name_en,$turn->address,$num],
                                'push_message' => [$turn->currency->name_en],
                            ];
                            (new Message())->syspublishsmsAll($msgArr);

                        }else{
                            //修改订单状态为失败
                            $turn->update(['status' => 3]);
                            //解锁钱包
                            $turn->wallet->update(['status' => 0]);
                        }
                    }
//                    else {
//                        //修改订单状态为失败
//                        $turn->update(['status' => 3]);
//                        //解锁钱包
//                        $turn->wallet->update(['status' => 0]);
//                    }

                    DB::commit();
                } catch (Exception $e) {
                    DB::rollback();
                    $msg = $e->getMessage();
                    dump($msg);
                }
            }
        }
    }
}
